package com.mald.plugin.data;

import com.mald.plugin.config.SystemConfig;
import com.mald.plugin.convert.DataConvertor;
import com.mald.plugin.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

/**
 * 数据操作
 */
public class DataProcessor {

    /**
     * 搜索想要的内容
     */
    public static void search(String searchText) {
        if (StringUtils.isEmpty(searchText)) return;
        Vector<Vector<String>> resultList = new Vector<>();
        DataCenter.DATA_MAP.forEach((key, node) -> {
            if (key.contains(searchText) || searchText.contains(key)) {
                resultList.add(DataConvertor.convert(node));
            }
        });
        DataCenter.TABLE_MODEL.setDataVector(resultList, DataCenter.HEADER);
    }

    /**
     * 重新加载数据
     */
    public static void reload() {
        try {
            String standardNameData = HttpClientUtil.createDefault().httpGet(
                    SystemConfig.FETCH_DATA_URL, 30000, null);
            ByteArrayInputStream bi = new ByteArrayInputStream(standardNameData.getBytes());
            BufferedReader reader = new BufferedReader(new InputStreamReader(bi));
            String str = null;
            String[] standardNameSplit = null;
            while ((str=reader.readLine())!=null) {
                standardNameSplit = str.split("-");
                if (StringUtils.isEmpty(standardNameSplit[0])
                        || StringUtils.isEmpty(standardNameSplit[1])
                        || StringUtils.isEmpty(standardNameSplit[2])) {
                    continue;
                }
                DataCenter.DATA_MAP.put(standardNameSplit[0], DataConvertor.convert(standardNameSplit));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 充值搜索的内容
     */
    public static void resetSearchResult() {
        DataCenter.TABLE_MODEL.setDataVector(null, DataCenter.HEADER);
    }

}
